<?php

    function BridgeBeforeFilterHook($ctrl)
    {
        if(!class_exists("BridgeConfig"))
        {
            App::import("Model","Bridge.BridgeConfig");
        }
        $cookieName = BridgeConfig::COOKIE_NAME;
        $sessionBridgeKey = "UserBridge.loginToken";
        if(isset($_COOKIE[$cookieName]))
        {
            if($ctrl->Session->read($sessionBridgeKey) != $_COOKIE[$cookieName])
            {
                
                $userId = cri("Bridge.UserBridge")->getUserFromToken($_COOKIE[$cookieName]);
                if($userId)
                {
                   $UserModel = cri("Users.User");
                   $UserModel->recursive = -1;
                   $user = $UserModel->findById($userId);
                   $ctrl->Session->write("Auth.User",$user['User']); 
                }
                $ctrl->Session->write($sessionBridgeKey,$_COOKIE[$cookieName]);
                if($userId)
                {
                    $ctrl->redirect("/".$ctrl->params['url']['url']);
                }
            }
        }else
        {
            //cookie not found, but we still we have bridge key.
            //So will need to logout user from here.
            if($ctrl->Session->read($sessionBridgeKey))
            {
                $ctrl->Session->delete("Auth");
                $ctrl->Session->delete($sessionBridgeKey);
                $ctrl->redirect("/".$ctrl->params['url']['url']);
            }
        }
    }
?>